<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="auto"
      size="small"
      class="ry_form">
      <el-form-item label="活动ID" prop="activityId">
        <el-input size="small" placeholder="请输入活动ID"/>
      </el-form-item>
      <el-form-item label="活动时间" prop="Time">
        <el-date-picker
          v-model="queryParams.Time"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="至"
          size="small"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
          align="right"
          @change="handleChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="flex_one tr">
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div :style="{ marginBottom: '10px', textAlign: 'right' }">
      <el-button type="primary" size="small" @click="showAddForm">活动创建</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="list"
      cell-class-name="my-cell">
      <el-table-column label="序号" type="index" :index="index => index + 1" />
      <el-table-column prop="activityId" label="活动ID" :width="100" />
      <el-table-column prop="activityName" label="活动名称" />
      <el-table-column label="活动时间">
        <template slot-scope="scope">
          <span>{{scope.row.activityStartTime}}</span>
          <span>至</span>
          <span>{{scope.row.activityEndTime}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="创建人" />
      <el-table-column label="操作" class-name="small-padding fixed-width" width="220" fixed="right">
        <template slot-scope="scope">
          <el-popover v-if="!+scope.row.isEnabled && +scope.row.status == 1 " placement="top-start" trigger="hover" content="该活动已开启过">
            <el-switch
              slot="reference"
              :style="{ marginRight: '5px' }"
              v-model="scope.row.status"
              active-value="0"
              disabled
              inactive-value="1" />
          </el-popover>
          <el-switch
            v-else
            :style="{ marginRight: '5px' }"
            :value="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleToggle(scope.row)" />
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="handleCopy(scope.row)">复制</el-button>
          <el-button size="mini" type="text" @click="handleDetail(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InBody v-show="total>0">
      <pagination
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </InBody>
    <el-dialog title="配置" :visible.sync="dialogVisible" width="800px" @close="closeAddForm">
      <el-form
        :model="addForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        ref="addForm"
        :disabled="editDisabled">
        <el-row>
          <el-col :span="16">
            <el-form-item label="活动名称" prop="activityName">
              <el-input v-model="addForm.activityName" placeholder="活动名称" :maxlength="20" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="活动时间" prop="Time">
          <el-date-picker
            v-model="addForm.Time"
            range-separator="至"
            type="datetimerange"
            size="small"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            placeholder="选择日期"
            :picker-options="{ disabledDate }" />
        </el-form-item>
        <template v-if="addForm.rechargeActivityRuleList.length">
          <el-form-item
            label="活动规则"
            prop="rechargeActivityRuleList">
            <el-row v-for="(item, index) in addForm.rechargeActivityRuleList" :key="index" align="middle">
              <el-col :span="2">档位{{index + 1}}：</el-col>
              <el-col :span="10">
                <el-row align="middle">
                  <el-col :span="4">
                    <span>每充值</span>
                  </el-col>
                  <el-col :span="18">
                    <el-form-item
                      :prop="`rechargeActivityRuleList[${index}].rechargeAmount`"
                      :rules="getRules(index, 'rechargeAmount')">
                      <el-input-number
                        v-model="addForm.rechargeActivityRuleList[index].rechargeAmount"
                        :min="0"
                        :step="1"
                        placeholder="请输入金额" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="1">
                    <span>元</span>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="10">
                <el-row align="middle">
                  <el-col :span="3">
                    <span>赠送</span>
                  </el-col>
                  <el-col :span="18">
                    <el-form-item
                      :prop="`rechargeActivityRuleList[${index}].giftAmount`"
                      :rules="getRules(index, 'giftAmount')">
                      <el-input-number
                        v-model="addForm.rechargeActivityRuleList[index].giftAmount"
                        :min="0"
                        :step="1"
                        placeholder="请输入金额" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="1">
                    <span>元</span>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="2">
                <el-button type="text" @click="handleRemoveRule(index)">删除档位</el-button>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleAddRule">新增档位</el-button>
          </el-form-item>
        </template>
        <el-form-item label="活动规则" v-else>
          <el-button type="primary" size="mini" @click="handleAddRule">新增档位</el-button>
        </el-form-item>
        <el-row :gutter="2">
          <el-col :span="12">
            <el-form-item label="展示入口" prop="showEntrance">
              <el-select v-model="addForm.showEntrance" placeholder="展示入口">
                <el-option v-for="item in entranceMap" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addForm.showEntrance === 'TO_BE_PAID'">
            <el-form-item label="倒计时(分钟)" prop="countdownCount">
              <el-input-number v-model="addForm.countdownCount" :min="1" :step="1" placeholder="请输入倒计时" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="充值规则：">
          <editor v-model="addForm.rechargeRules" :readOnly="editDisabled" :min-height="192" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAddForm">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dateUtil from '@/utils/DateUtil';
import { queryRechargeList, queryRechargeDetail, saveRecharge, updateRecharge, disableRecharge, enableRecharge } from '@/api/activity';
import { omit, countBy } from 'lodash'
import { mapGetters } from "vuex";
import { getBaseUrl } from "@/utils";

const EntranceMap = {
  'TO_BE_PAID': '待支付页',
  'PERSONAL_CENTER': '个人中心'
}
export default {
  computed:{ ...mapGetters(['userId']) },
  data() {
    const validateRuleList = (rule, value, callback) => {
      if (!value.length) return callback(new Error('请添加活动规则'));
      callback();
    }
    return {
      // 遮罩层
      loading: false,
      baseUrl: getBaseUrl(),
      entranceMap: Object.keys(EntranceMap).map(v => ({ label: EntranceMap[v], value: v })),
      // 时间配置
      pickerOptions: {
        shortcuts: dateUtil.getTimeShort2()
      },
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activityId: '',
        Time: [],
        createStartTime: '',
        createEndTime: ''
      },
      editId: '',
      dialogVisible: false,
      editDisabled: false,
      addForm: {
        activityName: '',
        Time: [],
        showEntrance: '',
        rechargeRules: '',
        countdownCount: '',
        rechargeActivityRuleList: []
      },
      rules: {
        Time: [{ required: true, message: '请选择活动时间', trigger: 'blur' }],
        activityName: [{ required: true, message: '请输入活动名称', trigger: 'blur' }],
        showEntrance: [{ required: true, message: '请选择展示入口', trigger: 'blur' }],
        countdownCount: [{ required: true, message: '请输入倒计时', trigger: 'blur' }],
        rechargeActivityRuleList: [{ validator: validateRuleList, trigger: 'blur' }]
      }
    };
  },
  async created() {
    this.getList().catch()
  },
  methods: {
    getRules(index, key) {
      const keyMap = {
        rechargeAmount: '充值金额',
        giftAmount: '赠送金额'
      }
      const validateRule = (rule, value, callback) => {
        let someIndex = null
        const hasSome = this.addForm.rechargeActivityRuleList.some((v, i) => {
          if (i !== index && +v[key] === value) {
            someIndex = i
            return true
          }
          return false
        })
        if (value === 0) return callback(new Error(keyMap[key]))
        if (hasSome) return callback(new Error('不同档位的规则不可一致'))
        callback()
      }
      return [
        { required: true, message: `请输入${keyMap[key]}`, trigger: 'blur' },
        { validator: validateRule, message: '不同档位的规则不可一致', trigger: 'blur' }
      ]
    },
    handleRemoveRule(index) {
      this.addForm.rechargeActivityRuleList.splice(index, 1)
    },
    handleAddRule() {
      const hasEmpty = this.addForm.rechargeActivityRuleList.some(item => !item.rechargeAmount || !item.giftAmount)
      if (hasEmpty) return this.$message.error('请填写完整档位信息')
      const countMap = countBy(this.addForm.rechargeActivityRuleList, item => `${item.rechargeAmount}-${item.giftAmount}`)
      if (Object.values(countMap).some(v => v > 1)) return this.$message.error('请勿重复添加档位')
      this.addForm.rechargeActivityRuleList.push({ rechargeAmount: 0, giftAmount: 0 })
    },
    disabledDate(date) {
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      return date < today; // 如果选择的日期早于今天，返回 true，禁用该日期
    },
    handleSubmit() {
      this.$refs['addForm'].validate(async (valid) => {
        if (!valid) return;
        if (this.editId) return this.updateActivity()
        return this.saveActivity()
      })
    },
    async updateActivity() {
      const params = {
        activityId: this.editId,
        activityStartTime: this.addForm.Time[0],
        activityEndTime: this.addForm.Time[1],
        activityName: this.addForm.activityName,
        showEntrance: this.addForm.showEntrance,
        rechargeRules: this.addForm.rechargeRules,
        countdownCount: this.addForm.countdownCount,
        rechargeActivityRuleList: this.addForm.rechargeActivityRuleList
      }
      const { code } = await updateRecharge(params)
      if (code !== 200) return;
      this.$message.success('修改成功')
      this.closeAddForm()
      return this.resetQuery()
    },
    async saveActivity() {
      const params = {
        activityStartTime: this.addForm.Time[0],
        activityEndTime: this.addForm.Time[1],
        activityName: this.addForm.activityName,
        showEntrance: this.addForm.showEntrance,
        rechargeRules: this.addForm.rechargeRules,
        countdownCount: this.addForm.countdownCount,
        rechargeActivityRuleList: this.addForm.rechargeActivityRuleList
      }
      const { code } = await saveRecharge(params)
      if (code !== 200) return;
      this.$message.success('添加成功')
      this.closeAddForm()
      return this.resetQuery()
    },
    resetFields () {
      this.editId = ''
      Object.assign(this.$data.addForm, this.$options.data().addForm)
    },
    showAddForm() {
      this.resetFields()
      this.dialogVisible = true
    },
    closeAddForm() {
      this.editId = ''
      this.dialogVisible = false;
      this.editDisabled = false
      this.resetFields();
    },
    indexMethod(index) {
      return index + 1;
    },
    // 编辑
    async handleEdit (recode) {
      const { code, data } = await queryRechargeDetail({ activityId: recode.activityId })
      if (code !== 200) return;
      this.editId = data.activityId
      this.addForm = {
        activityName: data.activityName,
        Time: [data.activityStartTime, data.activityEndTime],
        showEntrance: data.showEntrance,
        rechargeRules: data.rechargeRules,
        countdownCount: data.countdownCount,
        rechargeActivityRuleList: data.rechargeActivityRuleList
      }
      this.dialogVisible = true
    },
    // 复制
    async handleCopy (recode) {
      const { code, data } = await queryRechargeDetail({ activityId: recode.activityId })
      if (code !== 200) return;
      this.addForm = {
        activityName: data.activityName,
        Time: [data.activityStartTime, data.activityEndTime],
        showEntrance: data.showEntrance,
        rechargeRules: data.rechargeRules,
        countdownCount: data.countdownCount,
        rechargeActivityRuleList: data.rechargeActivityRuleList
      }
      this.dialogVisible = true
    },
    // 启用 or 禁用
    handleToggle (recode) {
      this.$confirm(`确定要${+recode.status ? '启用' : '禁用'}该活动吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (!+recode.status) {
          const { code } = await disableRecharge({ activityId: recode.activityId })
          if (code !== 200) return;
        } else {
          const { code } = await enableRecharge({ activityId: recode.activityId })
          if (code !== 200) return;
        }
        this.$message.success('操作成功')
        return this.resetQuery()
      }).catch(() => {
        return this.getList()
      })
    },
    // 详情
    async handleDetail (recode) {
      const { code, data } = await queryRechargeDetail({ activityId: recode.activityId })
      if (code !== 200) return;
      this.addForm = {
        activityName: data.activityName,
        Time: [data.activityStartTime, data.activityEndTime],
        showEntrance: data.showEntrance,
        rechargeRules: data.rechargeRules,
        countdownCount: data.countdownCount,
        rechargeActivityRuleList: data.rechargeActivityRuleList
      }
      this.dialogVisible = true
      this.editDisabled = true
    },
    /** 查询订单表列表 */
    async getList() {
      if (this.queryParams.Time) {
        this.queryParams.createStartTime = this.queryParams.Time[0]
        this.queryParams.createEndTime = this.queryParams.Time[1]
      }
      const queryParams = omit(this.queryParams, ['Time'])
      const { code, rows, total } = await queryRechargeList(queryParams)
      if (code !== 200) return;
      this.list = rows
      this.total = +total
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      Object.assign(this.$data.queryParams, this.$options.data().queryParams)
      this.handleQuery();
    },

    // 时间搜索条件change方法
    handleChange(value) {
      if (!value) {
        this.queryParams.createStartTime = '';
        this.queryParams.createEndTime = '';
      } else {
        this.queryParams.createStartTime = value[0];
        this.queryParams.createEndTime = value[1];
      }
      this.handleQuery();
    }
  }
};
</script>
<style lang="scss">
.product-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 340px;

  .product-item {
    margin: auto;
    width: 290px;

    .sp-data {
      font-size: 13px;
    }

    .quantity {
      font-weight: bold;
      font-size: 13px;
    }
  }
}

.note-title {
  font-weight: bold;
}

.el-table .my-cell {
  vertical-align: top
}

.el-link.el-link--default {
  color: #409eff;
}

.el-select {
  width: 100%;
}
.file-uploader {
  width: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;

  &:hover {
    border-color: #409EFF;
    i {
      color: #409EFF;
    }
  }

  .file-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .file {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
